package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"repairs/pkg/app"
	"repairs/pkg/e"
	"repairs/pkg/util"
	"repairs/service/user_service"
	"strconv"
)

type authJSON struct {
	Username string `valid:"MaxSize(50)" json:"username"`
	Password string `valid:"MaxSize(50)" json:"password"`
}
type registerJSON struct {
	Username string `valid:"Required; MaxSize(50)" json:"username"`
	Password string `valid:"MaxSize(50); Required" json:"password"`
}

func Login(c *gin.Context) {
	getAuth(c, true)
}

func Token(c *gin.Context) {
	getAuth(c, false)
}

//
//func Registration(c *gin.Context) {
//	appG := app.Gin{C: c}
//	valid := validation.Validation{}
//	var r registerJSON
//	if err := c.ShouldBindWith(&r, binding.JSON); err != nil {
//		app.MarkErrors(valid.Errors)
//		appG.Response(http.StatusBadRequest, e.InvalidParams, nil)
//		return
//	}
//	if ok, _ := valid.Valid(&r); !ok {
//		app.MarkErrors(valid.Errors)
//		appG.Response(http.StatusBadRequest, e.InvalidParams, nil)
//		return
//	}
//
//	userService := user_service.User{Username: r.Username, Password: r.Password}
//	if err := userService.Add(); err != nil {
//		appG.Response(http.StatusInternalServerError, e.ErrorAddUserFail, nil)
//		return
//	}
//
//	appG.Response(http.StatusOK, e.SUCCESS, nil)
//	return
//}

// @Summary Get Auth
// @Produce  json
// @Param username query string true "userName"
// @Param password query string true "password"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
func getAuth(c *gin.Context, login bool) {
	appG := app.Gin{C: c}
	var a authJSON
	var uid int
	var err error = nil
	// 1. 绑定参数并校验
	httpCode, errCode := app.BindAndValid(c, &a)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}
	if login {
		// 3. 登录校验
		uid, err = user_service.Check(a.Username, a.Password)
		if err != nil {
			appG.Response(http.StatusInternalServerError, e.ErrorAuthCheckTokenFail, nil)
			return
		}
		if uid <= 0 {
			appG.Response(http.StatusUnauthorized, e.ErrorAuth, nil)
			return
		}
	} else if a.Username == "" {
		a.Username = "anonymous"
	}
	// 4. 生成token
	token, err := util.GenerateToken(a.Username, login)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ErrorAuthToken, nil)
		return
	}
	data := map[string]string{
		"token": token,
	}
	if login {
		data["user_id"] = strconv.Itoa(uid)
	}
	appG.Response(http.StatusOK, e.SUCCESS, data)
}
